package com.franz.noteapp.compose.editNote.compose

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.animation.Animatable
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animate
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Save
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.franz.noteapp.bean.NoteBean
import com.franz.noteapp.compose.editNote.EditNoteEvent
import com.franz.noteapp.compose.editNote.EditNoteUiEvent
import com.franz.noteapp.compose.editNote.EditNoteViewModel
import com.franz.noteapp.ui.theme.NoteTheme
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun EditNotePage(
    navHostController: NavHostController,
    color:Int,
    viewModel: EditNoteViewModel = hiltViewModel()
){
    val title = viewModel.noteTitle.value//标题状态管理
    val content = viewModel.noteContent.value//内容状态管理
    val scope = rememberCoroutineScope()//协程
    val scaffoldState = rememberScaffoldState()//脚手架状态

    /**
     * 对当前笔记的背景颜色进行管理
     * 如果是新创建的一个笔记则默认使用随机颜色
     * 反之，从指定笔记进行导航路由，则使用传递的颜色参数*/
    val noteBackground = remember {
        Animatable(
            Color(
                if (color != -1)
                    color
                else
                    viewModel.noteColor.value
            )
        )
    }

    /**
     * 对事件流进行监听，一旦触发以下两个事件，则根据相应代码块进行执行*/
    LaunchedEffect(key1 = true){
        viewModel.eventFlow.collectLatest {
            when(it){
                is EditNoteUiEvent.ShowSnackBar -> {
                    scaffoldState.snackbarHostState.showSnackbar(it.message)
                }
                is EditNoteUiEvent.SaveNoteUi -> {
                    navHostController.navigateUp()
                }
            }
        }
    }

    Scaffold(
        /**
         * 保存按钮*/
        floatingActionButton = {
            FloatingActionButton(
                backgroundColor = NoteTheme.colors.onBackground,
                onClick = { viewModel.onEvent(EditNoteEvent.SaveNote) }
            ) {
                Icon(
                    imageVector = Icons.Default.Save,
                    contentDescription = "保存",
                    tint = NoteTheme.colors.textColor
                )
            }
        },
        scaffoldState = scaffoldState
    )
    {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(noteBackground.value)
                .padding(top = 45.dp, start = 16.dp, end = 16.dp, bottom = 16.dp)
        ) {
            /**
             * 顶部颜色条*/
            ColorList(colors = NoteBean.noteColor,viewModel.noteColor.value){ color->
                scope.launch {
                    noteBackground.animateTo(
                        targetValue = color,
                        animationSpec = tween(500)
                    )
                    viewModel.onEvent(EditNoteEvent.ChangeColor(color.toArgb()))
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            /**
             * 笔记标题*/
            TextField(
                value = title.text,
                textStyle = MaterialTheme.typography.h5,
                singleLine = true,
                onValueChange = { viewModel.onEvent(EditNoteEvent.EnterTitle(it)) },
                placeholder = { Text(text = title.hint, color = NoteTheme.colors.textColor) },
                colors = TextFieldDefaults.textFieldColors(
                    backgroundColor = Color.Transparent,
                    disabledIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent,
                    focusedIndicatorColor = Color.Transparent,
                    errorIndicatorColor = Color.Transparent,
                    cursorColor = Color.Black,//光标颜色

                ),
                modifier = Modifier.fillMaxWidth()

            )

            Spacer(modifier = Modifier.height(16.dp))

            /**
             * 笔记内容*/
            TextField(
                value = content.text,
                textStyle = MaterialTheme.typography.body1,
                singleLine = false,
                onValueChange = { viewModel.onEvent(EditNoteEvent.EnterContent(it)) },
                placeholder = { Text(text = content.hint, color = NoteTheme.colors.textColor) },
                colors = TextFieldDefaults.textFieldColors(
                    backgroundColor = Color.Transparent,
                    disabledIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent,
                    focusedIndicatorColor = Color.Transparent,
                    errorIndicatorColor = Color.Transparent,
                    cursorColor = Color.Black,//光标颜色

                ),
                modifier = Modifier.fillMaxWidth()
            )
        }
    }
}

/**
 * 顶部颜色条*/
@Composable
fun ColorList(colors:List<Color>,currentColor:Int,onChangeColor:(Color)->Unit){
    LazyRow(
        horizontalArrangement = Arrangement.SpaceBetween,
        modifier = Modifier.fillMaxWidth().padding(8.dp)
    ){
        items(colors.size){
            ColorItem(colors[it],currentColor){color->onChangeColor(color)}
        }
    }
}

/**
 * 单个颜色块*/
@Composable
fun ColorItem(color:Color,currentColor:Int,onChangeColor:(Color)->Unit){
    Box(
        modifier = Modifier
            .size(50.dp)
            .shadow(15.dp, CircleShape)
            .clip(CircleShape)
            .background(color)
            .border(
                width = 3.dp,
                shape = CircleShape,
                color = if (currentColor == color.toArgb()) {
                    NoteTheme.colors.textColor
                }
                else
                    Color.Transparent
            )
            .clickable { onChangeColor(color) }
    )
}